﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace System.Windows.Media.DirectShow
{
    internal class FiltersDictionary : Dictionary<String, IBaseFilter>, IFiltersDictionary
    {

        private FilterTypeComparer filterTypeComparer = new FilterTypeComparer();

        internal void RemoveByValue(IBaseFilter filter)
        {
            var list = (IEnumerable<KeyValuePair<String, IBaseFilter>>)this;
            foreach (string name in list.Where(k => k.Value == filter).Select(k => k.Key).ToArray())
                this.Remove(name);
        }

        internal IEnumerable<IBaseFilter> GetFiltersFromRenderer()
        {
            return this.Values.OrderByDescending(f => f, filterTypeComparer);
        }

        #region IEnumerable<IBaseFilter> Members

        IEnumerator<IBaseFilter> IEnumerable<IBaseFilter>.GetEnumerator()
        {
            return this.Values.GetEnumerator();
        }


        #endregion

        protected internal class FilterTypeComparer : IComparer<IBaseFilter>
        {
            #region IComparer<IBaseFilter> Members

            int IComparer<IBaseFilter>.Compare(IBaseFilter x, IBaseFilter y)
            {
                int xout = x.Pins.FindByDirection(PinDirection.Output).Count();
                int yout = y.Pins.FindByDirection(PinDirection.Output).Count();
                int xin = x.Pins.FindByDirection(PinDirection.Input).Count();
                int yin = y.Pins.FindByDirection(PinDirection.Input).Count();

                bool isSourceX = (xin == 0);
                bool isRenderX = (xout == 0);
                bool isTransfX = (xin > 0 && xout > 0);

                bool isSourceY = (yin == 0);
                bool isRenderY = (yout == 0);
                bool isTransfY = (yin > 0 && yout > 0);

                int vx = (isSourceX) ? -1 : (isTransfX) ? 0 : 1;
                int vy = (isSourceY) ? -1 : (isTransfY) ? 0 : 1;

                return vx.CompareTo(vy);
            }

            #endregion
        }
    }
}
